package com.winit.openapi.apiadapter.adapter;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.winit.common.spi.SPIException;
import com.winit.common.spi.command.GetByKeyCommand;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.erp.spi.user.vo.User;
import com.winit.openapi.constants.ApiConstant;
import com.winit.ums.spi.CustomerCompanyService;
import com.winit.ums.spi.UmsUserService;
import com.winit.ums.spi.commnad.CustomerCompanyQueryCommand;
import com.winit.ums.spi.distributor.DistributorService;
import com.winit.ums.spi.distributor.command.QueryDistributorByUsernameCommand;
import com.winit.ums.spi.distributor.vo.DistributorVo;
import com.winit.ums.spi.finance.FinanceUserService;
import com.winit.ums.spi.finance.command.QueryFinanceByCompanyIdCommand;
import com.winit.ums.spi.finance.command.QueryFinanceCommand;
import com.winit.ums.spi.finance.vo.FinanceBaseInfoVo;
import com.winit.ums.spi.vo.CustomerCompanyVo;
import com.winit.ums.spi.vo.user.UserVO;

/**
 * UMS用户关系服务适配，包括用户，公司，分销等适配
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * minghao.deng 	1.0  		2017年8月17日 	Created
 *
 * </pre>
 * @since 1.
 */
@Service("umsUserServiceAdapter")
public class UmsUserServiceAdapter {

    private static final Logger    logger = LoggerFactory.getLogger(UmsUserServiceAdapter.class);
    @Resource
    private UmsUserService         umsUserService;
    @Resource
    private CustomerCompanyService customerCompanyService;
    @Resource
    private DistributorService     distributorService;
    @Resource
    private FinanceUserService     financeUserService;

    /**
     * UMS通过用户名查询用户信息，并转换为ERP的User对象
     * 
     * @param requestMsg
     * @return
     */
    public User queryUserByNameAndPlatform(String userName, String platform) {
        if (StringUtils.isBlank(userName)) {
            return null;
        }
        if ("JX".equalsIgnoreCase(platform)) {
            QueryFinanceCommand financeCommand = new QueryFinanceCommand();
            financeCommand.setUserName(userName);
            FinanceBaseInfoVo financeUser = financeUserService.queryFinanceCustomer(financeCommand);
            if (null == financeUser) {
                logger.error("查询金融用户信息失败,账号：" + userName);
                return null;
            }
            return convertFinanceUser(financeUser);

        }
        GetByKeyCommand<String> userCommand = new GetByKeyCommand<String>();
        userCommand.setSearchKey(userName);
        UserVO userVo = null;

        try {
            userVo = umsUserService.queryByUsername(userCommand);
        } catch (SPIException e) {
            logger.info("不存在此账号的卖家，查询分销商,userName:" + userName);
        }
        // 如果用户为空，可能是分销商，再去分销商系统查用户
        if (null == userVo) {
            QueryDistributorByUsernameCommand disCommand = new QueryDistributorByUsernameCommand();
            disCommand.setUserName(userName);
            DistributorVo distributorVo = distributorService.queryDistributorByUsername(disCommand);
            if (distributorVo == null) {
                return null;
            }
            return convertDisToUser(distributorVo);
        }

        return convertUmsUser(userVo);

    }
    
    /**
     * UMS通过用户名查询用户信息，并转换为ERP的User对象
     * 
     * @param requestMsg
     * @return
     */
    public User queryFxUserByName(String userName) {
        if (StringUtils.isBlank(userName)) {
            return null;
        }

        // 如果用户为空，可能是分销商，再去分销商系统查用户
        QueryDistributorByUsernameCommand disCommand = new QueryDistributorByUsernameCommand();
        disCommand.setUserName(userName);
        DistributorVo distributorVo = distributorService.queryDistributorByUsername(disCommand);
        if (distributorVo == null) {
            GetByKeyCommand<String> userCommand = new GetByKeyCommand<String>();
            userCommand.setSearchKey(userName);
            UserVO userVo = null;

            try {
                userVo = umsUserService.queryByUsername(userCommand);
            } catch (SPIException e) {
                logger.info("查询卖家异常--：,userName:" + userName);
            }
            if (userVo == null) {
                logger.info("不存在此账号的分销商，查询卖家,userName:" + userName);
                return null;
            }
            return convertUmsUser(userVo);
        }
        return convertDisToUser(distributorVo);

    }
    
    /**
     * 查询分销商公司信息
     * @param user
     * @return
     */
    public Bpartner queryFxCompany(User user) {
        Bpartner bpartner = new Bpartner();
        bpartner.setAdUserId(user.getUserId());
        QueryDistributorByUsernameCommand disCommand = new QueryDistributorByUsernameCommand();
        disCommand.setUserName(user.getLoginName());
        DistributorVo distributorVo = distributorService.queryDistributorByUsername(disCommand);
        if (distributorVo == null) {
            logger.warn("查询分销商公司信息失败：账号：" + user.getLoginName());
            return null;
        }
        bpartner.setcBpartnerId(distributorVo.getcBpartnerId());
        bpartner.setAdClientId(Long.valueOf(ApiConstant.SELLER_CLIENTID));
        bpartner.setAdOrgId(ApiConstant.USER_ORG_ID);
        bpartner.setValue(distributorVo.getCode());
        bpartner.setName(distributorVo.getName());
        bpartner.setBpartnerGroup(distributorVo.getCustomerGroup());

        return bpartner;

    }

    /**
     * 根据用户获取用户的公司信息，并统一转换为ERP的Bpartner对象
     * 
     * @param user
     * @param platform
     * @return
     */
    public Bpartner queryBpartnerByUser(User user, String platform) {
        Bpartner bpartner = new Bpartner();
        bpartner.setAdUserId(user.getUserId());
        // 金选账号公司信息查询
        if (StringUtils.isNotBlank(platform) && platform.equalsIgnoreCase("JX")) {
            QueryFinanceByCompanyIdCommand financeInfoCommand = new QueryFinanceByCompanyIdCommand();
            financeInfoCommand.setCompanyId(user.getUmsCompanyId());
            FinanceBaseInfoVo financeCompany = financeUserService.queryFinanceCompanyByCompanyId(financeInfoCommand);
            if (null == financeCompany) {
                logger.error("查询金融用户公司信息失败,账号：" + user.getLoginName() + " 公司ID：" + user.getUmsCompanyId());
                return null;
            }
            bpartner.setcBpartnerId(user.getBpartnerId());
            bpartner.setAdClientId(Long.valueOf(ApiConstant.SELLER_CLIENTID));
            bpartner.setAdOrgId(ApiConstant.USER_ORG_ID);
            // bpartner.setValue(financeCompany.get);
            bpartner.setName(financeCompany.getCompanyName());
            // bpartner.setBpartnerGroup(financeCompany.getCustomerGroup());
        } else {
            // UmsCompanyId为空，说明用户为非分销商
            if (null != user.getUmsCompanyId()) {
                CustomerCompanyQueryCommand command = new CustomerCompanyQueryCommand();
                command.setCompanyId(user.getUmsCompanyId().intValue());
                CustomerCompanyVo customerCompany = customerCompanyService.queryByCompanyId(command);
                if (customerCompany == null) {
                    return null;
                }
                bpartner.setcBpartnerId(customerCompany.getcBpartnerId());
                bpartner.setAdClientId(Long.valueOf(ApiConstant.SELLER_CLIENTID));
                bpartner.setAdOrgId(ApiConstant.USER_ORG_ID);
                bpartner.setValue(customerCompany.getCode());
                bpartner.setName(customerCompany.getName());
                bpartner.setBpartnerGroup(customerCompany.getCustomerGroup());

            } else {// 分销商
                QueryDistributorByUsernameCommand disCommand = new QueryDistributorByUsernameCommand();
                disCommand.setUserName(user.getLoginName());
                DistributorVo distributorVo = distributorService.queryDistributorByUsername(disCommand);
                if (distributorVo == null) {
                    return null;
                }
                bpartner.setcBpartnerId(distributorVo.getcBpartnerId());
                bpartner.setAdClientId(Long.valueOf(ApiConstant.SELLER_CLIENTID));
                bpartner.setAdOrgId(ApiConstant.USER_ORG_ID);
                bpartner.setValue(distributorVo.getCode());
                bpartner.setName(distributorVo.getName());
                bpartner.setBpartnerGroup(distributorVo.getCustomerGroup());

            }
        }
        return bpartner;

    }

    private User convertUmsUser(UserVO umsUserVo) {
        User user = new User();
        user.setLoginName(umsUserVo.getUsername());
        user.setUserId(umsUserVo.getAdUserId());
        user.setBpartnerId(umsUserVo.getcBpartnerId());
        user.setEmail(umsUserVo.getEmail());
        user.setFrequency(umsUserVo.getFerquency());
        user.setToken(umsUserVo.getToken());
        user.setClientId(Long.valueOf(ApiConstant.SELLER_CLIENTID));
        user.setOrgId(umsUserVo.getOrganizationId() == null ? ApiConstant.USER_ORG_ID : umsUserVo.getOrganizationId());
        user.setUmsCompanyId(umsUserVo.getCompanyId());

        return user;
    }

    private User convertDisToUser(DistributorVo distributorVo) {
        User user = new User();

        user.setLoginName(distributorVo.getUserName());
        user.setUserId(distributorVo.getAdUserId());
        user.setBpartnerId(distributorVo.getcBpartnerId());
        user.setToken(distributorVo.getToken());
        user.setClientId(Long.valueOf(ApiConstant.SELLER_CLIENTID));
        user.setOrgId(ApiConstant.USER_ORG_ID);

        return user;
    }

    private User convertFinanceUser(FinanceBaseInfoVo financeUser) {

        User user = new User();
        user.setLoginName(financeUser.getUserName());
        // user.setUserId(financeUser.get);
        user.setBpartnerId(financeUser.getcBpartnerId());
        // user.setEmail(financeUser.get);
        // user.setFrequency(umsUserVo.getFerquency());
        user.setToken(financeUser.getToken());
        user.setClientId(Long.valueOf(ApiConstant.SELLER_CLIENTID));
        user.setOrgId(ApiConstant.USER_ORG_ID);
        user.setUmsCompanyId(financeUser.getFspCompanyId());

        return user;
    }

}
